import React, {useEffect, useState} from 'react';
import {Modal, Button} from 'antd';
import EditableTagGroup from "@/pages/components/EditableTagGroup";

export default function GroupModal(props) {
  const {visible, setVisible, dispatch} = props;
  const [groups, setGroups] = useState([]);
  const [original, setOriginal] = useState([]);

  function getAllGroups() {
    dispatch({
      type: "groupManage/getAll"
    }).then(res => {
      let names = res.map((t) => {
        return t.name
      });
      setGroups(names);
      setOriginal(names);
    });
  }


  useEffect(() => {
    console.log("组件加载时，运行一次该函数");
    getAllGroups();
  }, []);


  const showModal = () => {
    setVisible(true);
  };

  const handleOk = () => {
    let d = Array();
    groups.forEach((g) => {
      if (!original.includes(g)) {
        d.push(g);
      }
    });
    dispatch({
      type: "groupManage/createGroups",
      payload: {
        groups: d.join(",")
      }
    }).then(() => {
      setVisible(false);
    });
  };

  const handleCancel = () => {
    setVisible(false);
  };

  return (
    <Modal title="API分组" visible={visible} onOk={handleOk} onCancel={handleCancel}>
      <EditableTagGroup className='edit-tag' setTags={setGroups} tags={groups} type={'group'}/>
    </Modal>
  );
};
